<?php
namespace Client\Table;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\Adapter\AdapterAwareInterface;

use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;

use Zend\Db\Sql\Select;

use Zend\Db\TableGateway\Feature\RowGatewayFeature;
use Zend\Db\TableGateway\Feature\FeatureSet;

/**
 *
 * 公共 Table 类
 * 
 */
class CommonTable extends AbstractTableGateway implements AdapterAwareInterface
{
    protected $id = null;
    
    /**
     * @return the $id
     */
    public function getId()
    {
        return $this->id;
    }
    
    /**
     * @param field_type $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }
    /**
     * Set db adapter
     *
     * @param Adapter $adapter
     */
    public function setDbAdapter(Adapter $adapter)
    {
        $this->adapter = $adapter;
        $this->featureSet = new FeatureSet([new RowGatewayFeature($this->getId())]);
        $this->initialize();
    }

    protected function fetchPaginate($select, $query)
    {
        $paginatorAdapter = new DbSelect($select, $this->getAdapter());
        $paginator = new Paginator($paginatorAdapter);
        return $this->paginatorInit($query, $paginator);
    }
    
    protected function paginatorInit($query, $paginator)
    {
        (int) $page = !empty($query['page']) ? $query['page'] : 1;
        $paginator->setCurrentPageNumber($page);
        $count_per_page = !empty($query['count_per_page']) ? $query['count_per_page'] : 20;
        $paginator->setItemCountPerPage($count_per_page);
        return $paginator;
    }
    
    public function fetchIds()
    {
        $select = new Select($this->getTable());
        $select->columns(array($this->getId()));
        return $this->executeSelect($select);
    }
    
    public function getById($id)
    {
        $id  = (int) $id;
        $rowset = $this->select(array($this->getId() => $id));
        $row = $rowset->current();
        return $row;
    }
    
    public function updateById($data, $id)
    {
        return $this->update($data, array($this->getId() => $id));
    }
    
    protected static function resultSetToArray($resultSet) {
        $list = array();
        foreach($resultSet as $orderItem) {
            array_push($list, $orderItem);
        }
        return $list;
    }
    
    public function beginTransaction(){
        $this->adapter->getDriver()->getConnection()->beginTransaction();
    }
    public function commit(){
        $this->adapter->getDriver()->getConnection()->commit();
    }
    public function rollBack(){
        $this->adapter->getDriver()->getConnection()->rollBack();
    }
}